<?php
/**
* * Model Class
* 
* @author Guillermo Landín
* @link 
* 
* 
*/ 

class Wishlistsmodel extends Model {

    function __construct()
    {
        parent::Model();
        
        $this->CI =& get_instance(); 
    }   


    // returns the list products, grouped in an array of wishlists. 
	// list can be limited to items of a certain $wishlist_id
    function get_list($user_id=FALSE, $wishlist_id=FALSE){
    
        $this->db->select('wishlists.*, wishlists_products.DateAdded_Wishlists, products.id_Products AS id, Name_Products AS title, CONCAT(Introduction_Products, Description_Products) AS text, Main_Image AS image', FALSE)
                ->from('wishlists')
                ->join('wishlists_products', 'wishlists.id_Wishlists=wishlists_products.id_Wishlists', 'left')      
                ->join('products', 'wishlists_products.id_Products = products.id_Products', 'left')
                ->join('categories', 'products.id_Categories = categories.id_Categories', 'left')
                ->where('id_Users', $user_id)                                          
				->where('(Active_Products=1 OR Active_Products IS NULL)', NULL, FALSE)
				->where('(Active_Categories=1 OR Active_Categories IS NULL)', NULL, FALSE)
                ->order_by('wishlists.id_Wishlists')
                ->order_by('DateAdded_Wishlists', "DESC");

        if ($wishlist_id != FALSE) {
            $this->db->where('wishlists.id_Wishlists', $wishlist_id);
         }
		 
        $query = $this->db->get();

        $result = $query->result_array();     

		//die($this->db->last_query());

        $grouped_result = $this->group_into_wishlists($result);

        return $grouped_result;

    }

    //receives a db result and returns a new array, with results grouped in arrays of months   
    private function group_into_wishlists($result = array())
    {
        
        $grouped_array = array();

        foreach($result as $row) 
        {
             $display = $row['Title_Wishlists'];
             $param = $row['id_Wishlists'];

             if (@$grouped_array[count($grouped_array)-1]["params"] == $param)
             {
                    $grouped_array[count($grouped_array)-1]["items"][] = $row;

             } else {
                
                $grouped_array[] = array(
                                        "name" => $display,
                                        "params" => $param,     
                                        "items" => (is_null($row['id'])) ? array() : array($row)
                                        );
                
             }

        }

        return $grouped_array;

    }


	// Returns the id of the oldest list from user. 
	// If no list exists, it creates one.
    public function get_default_wishlist($user_id=FALSE){

        $this->db->select('id_Wishlists')
                ->from('wishlists')
                ->where('id_Users', $user_id)
                ->order_by('id_Wishlists')
                ->limit(1);

        $query = $this->db->get();

        $result = $query->row_array();

        if (empty($result)) return $this->_set_default_wishlist($user_id);
        else return $result['id_Wishlists'];

    }

    private function _set_default_wishlist($user_id=FALSE){

        //$new_id =  uniqid('',TRUE);  

        $data = array(
                       //'id_Wishlists' => $new_id,
                       'id_Users' => $user_id,
                       'Title_Wishlists' => DEFAULT_WISHLIST_TITLE
                    );

        $this->db->insert('wishlists', $data); 

        return $this->db->insert_id();

    }

    public function get_wishlist_info($wishlist_id=FALSE, $user_id=FALSE){

        $this->db->select('*')
                ->from('wishlists')
                ->where('id_Wishlists', $wishlist_id)
                ->where('id_Users', $user_id);  

        $query = $this->db->get();
        $result = $query->row_array();

        return $result;

    }
    
    public function add_product($product_id=FALSE, $wishlist_id=FALSE, $user_id=FALSE)
    {
		$valid_wishlist = $this->get_wishlist_info($wishlist_id, $user_id);
		if (empty($valid_wishlist)) return false;

        if ($this->_check_if_product_exists($product_id, $wishlist_id) !== TRUE){

            $this->db->set('id_Wishlists', $wishlist_id); 
            $this->db->set('id_Products', $product_id); 
            $this->db->set('DateAdded_Wishlists', 'NOW()', FALSE); 
            $this->db->insert('wishlists_products');    
			$this->db->last_query();
        }        

    }
    public function delete_product($product_id=FALSE, $wishlist_id=FALSE, $user_id=FALSE)
    {

        $this->db->select('*')
                ->from('wishlists')
                ->where('id_Wishlists', $wishlist_id)
                ->where('id_Users', $user_id);  

        $query = $this->db->get();
        $result = $query->row_array();

        if (!empty($result)) {

            $this->db->where('id_products', $product_id);
            $this->db->where('id_wishlists', $wishlist_id);
            $this->db->delete('wishlists_products');           

        }

    }
    public function move_product($product_id=FALSE, $from_wishlist_id=FALSE, $to_wishlist_id=FALSE, $user_id=FALSE){

        if($this->_check_if_product_exists($product_id, $to_wishlist_id)==FALSE ) { 

            $this->db->set('id_Wishlists', $to_wishlist_id);
            $this->db->where('id_Products', $product_id);        
            $this->db->where('id_Wishlists', $from_wishlist_id);        
            $this->db->update('wishlists_products'); 

        }

    }
    private function _check_if_product_exists($product_id=FALSE, $wishlist_id=FALSE){

        $this->db->select('*')
                ->from('wishlists_products')
                ->where('id_Products', $product_id)
                ->where('id_Wishlists', $wishlist_id);  

        $query = $this->db->get();
        $result = $query->row_array();

        if (empty($result))return FALSE;
        else return TRUE; 

    }
    private function _check_if_wishlist_name_exists($wishlist_name=FALSE, $user_id=FALSE){

        $this->db->select('id_Wishlists')
                ->from('wishlists')
                ->where('id_Users', $user_id)
                ->where('Title_Wishlists', $wishlist_name);  

        $query = $this->db->get();
        $result = $query->row_array();

        if (empty($result)){
            return FALSE;
        }else{ 
            $row = $query->row();
            return $row->id_Wishlists; 
        }

    }
    public function get_wishlists($user_id = FALSE, $wishlist_id = NULL){

        $this->db->select('id_Wishlists, Title_Wishlists')
                ->from('wishlists')
                ->where('id_Users', $user_id);  
		if ($wishlist_id!==NULL){
			$this->db->where('id_Wishlists', $wishlist_id);  
		}

        $query = $this->db->get();

        $result = $query->result_array();
        
        return $result;

    }
                                   
    public function create_new_wishlist($wishlist_name=FALSE, $user_id=FALSE)
    {

        //$existing_list_id = $this->_check_if_wishlist_name_exists($wishlist_name, $user_id);

        //if($existing_list_id==FALSE){

            $this->db->set('id_Users', $user_id); 
            $this->db->set('Title_Wishlists', $wishlist_name); 
            $this->db->insert('wishlists');

            return $this->db->insert_id(); 

        //} else {

        //    return $existing_list_id;

        //}
        
    }
        
    public function delete_wishlist($wishlist_id=FALSE, $user_id=FALSE)
    {
        $this->db->where('id_Users', $user_id); 
        $this->db->where('id_Wishlists', $wishlist_id); 
        $this->db->delete('wishlists');    

        $this->delete_wishlist_products($wishlist_id);
    }
     
    public function delete_wishlist_products($wishlist_id=FALSE)
    {
        $this->db->where('id_Wishlists', $wishlist_id); 
        $this->db->delete('wishlists_products');    
    }

    public function remove_product($product_id=FALSE, $wishlist_id=FALSE, $user_id=FALSE)
    {

        $this->db->query("
        DELETE wishlists_products.*
        FROM wishlists_products
        LEFT JOIN wishlists ON wishlists_products.id_Wishlists = wishlists.id_wishlists
        WHERE wishlists_products.id_Wishlists = '$wishlist_id'
        AND id_Products = '$product_id'
        AND id_Users = '$user_id'
        "); 

        // there's no support for delete with join in code igniter. bummer...
        //$this->db->from('wishlists_products');
        //$this->db->join('wishlists', 'wishlists_products.id_Wishlists = wishlists.id_wishlists', 'left');
        //$this->db->where('id_Wishlists', $wishlist_id);                                 
        //$this->db->where('id_Products', $wishlist_id);                           
        //$this->db->where('id_User', $user_id);                           
        //$this->db->delete('wishlists_products');
                                                 
    }



/***********************************   
*   Sub-menu functions
***********************************/

    //returns an array of wishlists with fields 'name', 'controller' and 'param'
    public function get_submenu_wishlists($user_id = FALSE){

        $result = $this->get_wishlists($user_id);

        foreach($result as &$row){
            $row = array( 
                            'name' => $row['Title_Wishlists'], 
                            'controller' => 'wishlist/view/'.$row['id_Wishlists'], 
                            'param' => $row['id_Wishlists']
                            );
        }

        return $result;

    }


/*
    //returns an array of items under the given category. might be subcategories or products
    public function get_submenu_categories($id = FALSE, $prod_id = FALSE){

        $result = $this->get_all_categories();

        foreach($result as &$row){
            $row = array( 
                            'name' => $row['title'], 
                            'controller' => 'products/categories/'.$row['id'], 
                            'param' => $row['id']
                            );
        }

        //set the selected item and it's content
        foreach($result as &$item){

            if ( $item['param'] == $id) { 

                $subitems = $this->get_subcategories($id); 

                if (!empty($subitems)) { // if there are subcategories, show them

                    $cat_info = $this->get_category_info($id);
                    $parent_name = url_title($cat_info['name'], '_', TRUE);

                    foreach($subitems as &$subitem){
                        $subitem = array( 
                                        'name' => $subitem['title'], 
                                        'controller' => 'products/categories/'.$parent_name.'/'.$subitem['id'], 
                                        'param' => $subitem['id']
                                        );
                    }

                } else { // else, show the products

                    $subitems = $this->get_products_by_category($id); 
                    foreach($subitems as &$subitem){
                        $subitem = array( 
                                        'name' => $subitem['title'], 
                                        'controller' => 'products/view/'.$subitem['id'], 
                                        'param' => $subitem['id']
                                        );
                        if (($prod_id != FALSE) && ($subitem['param'] == $prod_id)) $subitem['selected'] = TRUE;
                    }
                }


                $item['selected'] = TRUE;
                $item['content'] = $subitems;

            }

        }


        return $result;

    }

    //returns the products submenu for given subcategory
    public function get_submenu_subcategories($id = FALSE, $prod_id = FALSE){

        $parent_info = $this->get_subcategory_info($id);
        $parent_id = $parent_info['parent_id'];

        $result = $this->get_submenu_categories($parent_id);
        
        //set the selected item and it's content
        foreach($result as &$item){
         
            if ($item['param'] == $parent_id) { 

                foreach($item['content'] as &$subitem){

                    if ($subitem['param'] == $id) { 

                        $products = $this->get_products_by_subcategory($id); 

                        foreach($products as &$product){
                            $product = array( 
                                            'name' => $product['title'], 
                                            'controller' => 'products/view/'.$product['id'], 
                                            'param' => $product['id']
                                            );
                            if (($prod_id != FALSE) && ($product['param'] == $prod_id)) $product['selected'] = TRUE;

                        }

                        $subitem['selected'] = TRUE;
                        $subitem['content'] = $products;


                    }

                }
            }
        }

        return $result;

    } 

    //returns an array of applications with fields 'name', 'controller' and 'param'
    public function get_submenu_applications($id = FALSE){
        
        $result = $this->get_all_applications();

        foreach($result as &$row){
            $row = array( 
                            'name' => $row['title'], 
                            'controller' => 'products/applications/'.$row['id'], 
                            'param' => $row['id']
                            );
        }

        //set the selected item
        foreach($result as &$item){

            if ( $item['param'] == $id) $item['selected'] = TRUE;

        }
                       
        return $result;    

    }

    //returns an array of one-off-products with fields 'name', 'controller' and 'param'
    public function get_submenu_one_off(){

        $result = $this->get_one_off_products();

        foreach($result as &$row){
            $row = array( 
                            'name' => $row['title'], 
                            'controller' => 'products/view/'.$row['id'], 
                            'param' => $row['id']
                            );
        }

        return $result;

    }

*/

}
